package omg.loot;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;

public class Sprite {
   protected FloatBuffer texCoords; //tekstuurin sijainti atlaksessa
   protected FloatBuffer vertices;
   protected final float leveys, korkeus;

   public Sprite(final float x, final float y, final float leveys, final float korkeus) {
      //Rajataan tekstuuri atlaksesta (skaala 0.0-1.0 väliltä):
      final float texture[] = {
            //Mapping coordinates for the vertices
            x/TextureManager.tAtlasWidth, y/TextureManager.tAtlasHeight,
            x/TextureManager.tAtlasWidth, (y+korkeus)/TextureManager.tAtlasHeight,
            (x+leveys)/TextureManager.tAtlasWidth, (y+korkeus)/TextureManager.tAtlasHeight,
            (x+leveys)/TextureManager.tAtlasWidth, y/TextureManager.tAtlasHeight,
      };
      //Luodaan tekstuuribufferi:
      final ByteBuffer byteBuf1 = ByteBuffer.allocateDirect(texture.length * 4);
      byteBuf1.order(ByteOrder.nativeOrder());
      texCoords = byteBuf1.asFloatBuffer();
      texCoords.put(texture);
      texCoords.position(0);

      //Luodaan verticet:
      this.leveys = leveys;
      this.korkeus = korkeus;
      final float centerX = leveys*0.5f;
      final float centerY = korkeus*0.5f;
      final float[] vt = new float[8];
      vt[0] = -centerX;       vt[1] = -centerY;  // 0, Top Left
      vt[2] = -centerX;       vt[3] = korkeus-centerY;  // 1, Bottom Left
      vt[4] = leveys-centerX; vt[5] = korkeus-centerY;  // 2, Bottom Right
      vt[6] = leveys-centerX; vt[7] = -centerY;  // 3, Top Right
      //Luodaan vertexBufferi:
      final ByteBuffer byteBuf2 = ByteBuffer.allocateDirect(vt.length * 4);
      byteBuf2.order(ByteOrder.nativeOrder());
      vertices = byteBuf2.asFloatBuffer();
      vertices.put(vt);
      vertices.position(0);
   }

   public void prepareForBatch(final int batchSize) {
      //Luodaan tekstuuribufferi:
      final ByteBuffer byteBuf1 = ByteBuffer.allocateDirect(texCoords.capacity() * 4 * batchSize);
      byteBuf1.order(ByteOrder.nativeOrder());
      final FloatBuffer temp = byteBuf1.asFloatBuffer();
      for (int i = 0; i < batchSize; i++) {
         temp.put(texCoords);
         texCoords.position(0);
      }
      temp.position(0);
      texCoords = temp;
   }
}